/**
 * 导航视图
 */
function scNavView(){
    var com = scCommon.instance();
    var crEle = com.crEle;

    var box = null;
    var body = null;
    var preview = null;

    var tab = null;
    var lastTabItem = null;
    var lastWrapper = null;

    var delayTask = null;

    var list = [
        {label: "标题", class: "step-1", command: "getAllTitleInfo", active: true},
        {label: "页面", class: "step-2", command: "getPagePreview"},
        {label: "结果", class: "step-3", command: "find"}
    ]

    var listener = null;

    /**
     * 创建视图
     * @param {*} option
     * @returns 
     */
    this.createView = function(option){
        option = option ? option : {};
        listener = option.listener;

        box = crEle(null, "sc-nav-view");

        var row = crEle(null, "sc-nav-row");
        var input = crEle("input");

        input.type = "text";
        input.placeholder = "搜索文档";
        input.addEventListener("keydown",(e)=>{
            if(e.key.toLowerCase() != "enter") return;
            let result = listener("find", input.value);
            tab.selectTab(list.find(item=>item.label=="结果").source, {data: result});
        });

        row.appendChild(input);
        box.appendChild(row);

        setTimeout(()=>{
            input.focus();
        }, 500);

        option.wrapHeight -= row.clientHeight;

        tab = new navTab(option);
        box.appendChild(tab.getTabNode());

        body = tab.getTabBodyNode();

        return box;
    }

    /**
     * 选项卡
     */
    function navTab(option){
        var tab = crEle(null, "sc-nav-tab");
        var tabHeadRow = crEle(null, "sc-nav-row");
        var tabBodyRow = crEle(null, "sc-nav-row,sc-row-direction-column");

        var item = null;
        for(var i in list){
            item = list[i];

            let label = crEle("label", item.class);
            label.innerText = item.label;
            tabHeadRow.appendChild(label);

            let content = crEle(null, "sc-nav-content");
            item.source = label;
            item.target = content;
    
            tabBodyRow.appendChild(content);

            if(item.active){
                content.classList.add("active");
                lastTabItem = item;
            }
        }

        var active = crEle("div", "sc-nav-active," + lastTabItem.class);
        tabHeadRow.appendChild(active);

        tabHeadRow.addEventListener("click",(e)=>{
            if(e.target.tagName.toLowerCase() == "label"){
                this.selectTab(e.target, option);
            }
        });

        tabBodyRow.addEventListener("scroll", (e)=>{
            if(lastTabItem.label == "页面"){
                if(e.target.scrollTop >= preview.scrollHeight - body.clientHeight){
                    if(delayTask){
                        clearTimeout(delayTask);
                        delayTask = null;
                    }

                    delayTask = setTimeout(()=>{
                        afterSwitchTab(lastTabItem, option.listener, {plus: 6});
                    }, 200);
                }
            }
        });

        tab.appendChild(tabHeadRow);
        tab.appendChild(tabBodyRow);

        this.getTabNode = function(){
            return tab;
        }

        this.getTabBodyNode = function(){
            return tabBodyRow;
        }

        this.selectTab = function(node, opt){
            let clazz = node.getAttribute("class");
            active.classList.remove(lastTabItem.class);
            active.classList.add(clazz);

            list.forEach(item=>{
                if(item.source == node){
                    item.target.classList.add("active");
                    lastTabItem = item;
                }else{
                    item.target.classList.remove("active");
                }
            });

            let height = option.wrapHeight - tabHeadRow.clientHeight - 35;
            tabBodyRow.style.height = height + "px";

            afterSwitchTab(lastTabItem, option.listener, opt);
        }

        afterSwitchTab(lastTabItem, option.listener, null);
    }

    /**
     * 单个页面预览视图大小
     */
    var size = {
        width: 120,
        height: 170,
        outerHeight: 210,
    };

    /**
     * 切换tab后
     * @param {*} item 
     * @param {*} listener
     * @param {*} option 
     */
    var afterSwitchTab = function(item, listener, option){
        option = option ? option : {};
        
        if(item.label == "标题"){
            getTitles();
        }else if(item.label == "页面"){   
            var count = Math.ceil(body.clientHeight / size.outerHeight);
            preview = item.target.querySelector(".sc-page-preview");
            var start = preview ? preview.querySelectorAll(".sc-image-wrapper").length : 0;
            var range = null;

            if(option.plus){
                range = calcRange(start + 1, start + option.plus);
            }else if(start == 0){
                range = calcRange(start + 1, start + count);
            }else{
                return;
            }

            var pageInfo = listener(item.command, {range: range});
            if(!pageInfo || pageInfo.length == 0) return;

            if(!preview){
                preview = crEle("div", "sc-page-preview");
                item.target.appendChild(preview);
                preview.addEventListener("click",(e)=>{
                    if(e.target.parentNode.classList.contains("sc-image-wrapper")){
                        if(lastWrapper){
                            lastWrapper.classList.remove("active");
                        }

                        e.target.parentNode.classList.add("active");
                        lastWrapper = e.target.parentNode;

                        let pageIndex = e.target.parentNode.getAttribute("data-index");
                        listener("locatePage", {pageIndex: pageIndex});
                    }
                });
            }else if(!option.plus){
                preview.innerHTML = "";
            }

            for(var i in pageInfo){
                let wrapper = crEle("div", "sc-image-wrapper");
                let img = crEle("img");
                let pageIndex = crEle("div", "sc-page-index");
                
                img.src = pageInfo[i];
                img.style.width = size.width + "px";
                img.style.height = size.height + "px";

                pageIndex.innerText = i;
                wrapper.setAttribute("data-index", i);

                wrapper.appendChild(img);
                wrapper.appendChild(pageIndex);
                preview.appendChild(wrapper);
            }
        }else if(item.label == "结果"){
            if(option.data){
                item.target.innerHTML = "";
            }
            
            let data = option.data;

            let countNode = crEle("div", "sc-nav-find-count");
            countNode.innerText = "共找到 " + data.count + "条结果：";

            item.target.appendChild(countNode);

            let area = null;
            let page = null;
            let index = 0;

            for(let i in data.fragments){
                area = data.fragments[i];

                for(let j in area){
                    page = area[j];
                    for(let k in page){
                        let row = page[k];

                        let node = crEle("div", "sc-nav-find-result");
                        node.innerText = row.text;

                        item.target.appendChild(node);

                        row.__index = ++index;

                        node.addEventListener("click", (e)=>{
                            e.target.classList.add("active");

                            if(lastFind.node){
                                lastFind.node.classList.remove("active");
                            }

                            if(lastFind.fragment){
                                lastFind.fragment.highlight = false;
                            }

                            row.highlight = true;

                            listener("find", null, {
                                type: row.__index < lastFind.index ? "prev" : "next",
                                pageRange: [row.offset.pageIndex],
                                highlightFindZone: true,
                                lastBoundRect: row.boundRect
                            });

                            lastFind.index = row.__index;
                            lastFind.fragment = row;
                            lastFind.node = e.target;
                        })
                    }
                }
            }
        }
    }

    /**
     * 查找结果最后点击属性
     */
    var lastFind = {};

    /**
     * 标题集合
     */
    var titles = {};

    /**
     * 最后一个选择的标题
     */
    var lastSelTitle = {};

    /**
     * 计算分页
     * @param {*} start 
     * @param {*} end 
     * @returns 
     */
    var calcRange = function(start, end){
        var range = [];

        for(var i = start; i <= end; i++){
            range.push(i);
        }

        return range;
    }

    /**
     * 通知
     * @param {*} eventType 
     * @param {*} opt 
     */
    this.notify = function(eventType, opt){
        if(eventType == "load"){
            if(preview){
                preview.innerHTML = "";
            }
            
            afterSwitchTab(lastTabItem, listener);
        }else if(eventType == "titleChange"){
            getTitles(opt.pageIndex);
        }
    }

    /**
     * 获取标题
     * @param {*} pageIndex 
     * @returns 
     */
    var getTitles = function(pageIndex){
        let range = null;
        if(pageIndex){
            range = [pageIndex];
        }

        let titleList = listener("getTitles", {range: range});
        if(lastTabItem.label != "标题") return;
        
        if(pageIndex){
            titles[pageIndex] = titleList[pageIndex];
        }else{
            titles = titleList;
        }

        lastTabItem.target.innerHTML = "";

        let title = null;
        let rowNode = null;
        for(let i in titles){
            for(let j in titles[i]){
                title = titles[i][j];
                rowNode = createTitleRow(title);
                lastTabItem.target.appendChild(rowNode);
            }
        }
    }

    /**
     * 创建标题节点
     * @param {*} title 
     * @returns 
     */
    var createTitleRow = function(title){
        let row = crEle("div", "sc-nav-title");
        let text = crEle("div", "sc-nav-tl," + title.titleType.toLowerCase());
        
        text.innerText = title.titleContent;

        row.appendChild(text);

        row.addEventListener("click", (e)=>{
            e.currentTarget.classList.add("active");

            if(lastSelTitle.node){
                lastSelTitle.node.classList.remove("active");
            }

            lastSelTitle.node = e.currentTarget;

            listener("locateRow", {
                lastBoundRect: title.boundRect,
                pageRange: [title.pageIndex]
            });
        });

        return row;
    }


}